<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-bounce.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"ipvb.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false,"b2t":true,"scrollpercent":true},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="1. Java NIO Channel1.1. Java NIO Channel的特点和老的OIO相比，通道和NIO流（非阻塞IO）主要有以下几点区别： （1）OIO流一般来说是单向的（只能读或者写），通道可以读也可以写。 （2）OIO流值读写阻塞的，而通道可以异步读写。 （3）通道总是基于缓冲区Buffer来读写。 1.2. Channel类型下面列出Java NIO中最重要的集中Channel">
<meta property="og:type" content="article">
<meta property="og:title" content="Java NIO Channel">
<meta property="og:url" content="https://ipvb.gitee.io/blog/2020/05/23/Java%20NIO%20Channel/index.html">
<meta property="og:site_name" content="Chenyumeng的博客">
<meta property="og:description" content="1. Java NIO Channel1.1. Java NIO Channel的特点和老的OIO相比，通道和NIO流（非阻塞IO）主要有以下几点区别： （1）OIO流一般来说是单向的（只能读或者写），通道可以读也可以写。 （2）OIO流值读写阻塞的，而通道可以异步读写。 （3）通道总是基于缓冲区Buffer来读写。 1.2. Channel类型下面列出Java NIO中最重要的集中Channel">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/scatter.png">
<meta property="og:image" content="https://ipvb.gitee.io/blog/assets/img/gather.png">
<meta property="article:published_time" content="2020-05-23T03:14:53.000Z">
<meta property="article:modified_time" content="2020-07-04T11:50:27.263Z">
<meta property="article:author" content="Chenyumeng">
<meta property="article:tag" content="笔记">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="NIO">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://ipvb.gitee.io/blog/assets/img/scatter.png">

<link rel="canonical" href="https://ipvb.gitee.io/blog/2020/05/23/Java%20NIO%20Channel/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>Java NIO Channel | Chenyumeng的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <link rel="stylesheet" href="/dist/css/share.min.css">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chenyumeng的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">热爱自己，热爱生活</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">29</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">1</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">32</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="search-pop-overlay">
  <div class="popup search-popup">
      <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

  </div>
</div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/chen-yumeng" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://ipvb.gitee.io/blog/2020/05/23/Java%20NIO%20Channel/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/touxiang.JPG">
      <meta itemprop="name" content="Chenyumeng">
      <meta itemprop="description" content="用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chenyumeng的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java NIO Channel
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-05-23 11:14:53" itemprop="dateCreated datePublished" datetime="2020-05-23T11:14:53+08:00">2020-05-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-04 19:50:27" itemprop="dateModified" datetime="2020-07-04T19:50:27+08:00">2020-07-04</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index"><span itemprop="name">学习</span></a>
                </span>
            </span>

          
            <span id="/blog/2020/05/23/Java%20NIO%20Channel/" class="post-meta-item leancloud_visitors" data-flag-title="Java NIO Channel" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span><br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>8.1k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>7 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="1-Java-NIO-Channel"><a href="#1-Java-NIO-Channel" class="headerlink" title="1. Java NIO Channel"></a>1. <strong>Java NIO Channel</strong></h3><h4 id="1-1-Java-NIO-Channel的特点"><a href="#1-1-Java-NIO-Channel的特点" class="headerlink" title="1.1. Java NIO Channel的特点"></a>1.1. <strong>Java NIO Channel的特点</strong></h4><p>和老的OIO相比，通道和NIO流（非阻塞IO）主要有以下几点区别：</p>
<p>（1）OIO流一般来说是单向的（只能读或者写），通道可以读也可以写。</p>
<p>（2）OIO流值读写阻塞的，而通道可以异步读写。</p>
<p>（3）通道总是基于缓冲区Buffer来读写。</p>
<h4 id="1-2-Channel类型"><a href="#1-2-Channel类型" class="headerlink" title="1.2. Channel类型"></a>1.2. <strong>Channel类型</strong></h4><p>下面列出Java NIO中最重要的集中Channel的实现：</p>
<p>（1）FileChannel</p>
<p>（2）DatagramChannel</p>
<p>（3）SocketChannel</p>
<p>（4）ServerSocketChannel</p>
<a id="more"></a>

<p>四种通道的说明如下：</p>
<p>FileChannel用于文件的数据读写。</p>
<p>DatagramChannel用于UDP的数据读写。</p>
<p>SocketChannel用于TCP的数据读写。</p>
<p>ServerSocketChannel允许我们监听TCP链接请求，每个请求会创建会一个SocketChannel。</p>
<p>这个四种通道，涵盖了 UDP 和 TCP网络 IO以及文件 IO的操作。下面从通道的新建、读取、写入、关闭等四个操作，四种通道进行简单的介绍。</p>
<h4 id="1-3-FileChannel"><a href="#1-3-FileChannel" class="headerlink" title="1.3. FileChannel"></a>1.3. <strong>FileChannel</strong></h4><p>FileChannel 是操作文件的Channel，我们可以通过 FileChannel 从一个文件中读取数据，也可以将数据写入到文件中。</p>
<p>注意，FileChannel 不能设置为非阻塞模式。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TestChannelFile</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 操作一：打开 FileChannel通道</span></span><br><span class="line">    RandomAccessFile accessFile = <span class="keyword">new</span> RandomAccessFile(<span class="string">"ChannelFile.txt"</span>, <span class="string">"rw"</span>);</span><br><span class="line">    FileChannel fileChannel = accessFile.getChannel();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 操作二：读取数据</span></span><br><span class="line">    ChannelFileRead(fileChannel);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 操作三：写入数据</span></span><br><span class="line">    String newData = <span class="string">"New String to write to file..."</span> + System.currentTimeMillis();</span><br><span class="line">    ByteBuffer buffer = ByteBuffer.allocate(<span class="number">48</span>);</span><br><span class="line">    buffer.clear();</span><br><span class="line">    buffer.put(newData.getBytes());</span><br><span class="line">    buffer.flip();</span><br><span class="line">    <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">        fileChannel.write(buffer);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 操作四：关闭</span></span><br><span class="line">    <span class="comment">// 当我们对 FileChannel 的操作完成后，必须将其关闭。</span></span><br><span class="line">    fileChannel.close();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 操作五：强制刷新磁盘</span></span><br><span class="line">    <span class="comment">// FileChannel的force()方法将所有未写入的数据从通道刷新到磁盘中。</span></span><br><span class="line">    <span class="comment">// 在你调用该force()方法之前，出于性能原因，操作系统可能会将数据缓存在内存中，因此您不能保证写入通道的数据实际上写入磁盘</span></span><br><span class="line">    fileChannel.force(<span class="keyword">true</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">ChannelFileRead</span><span class="params">(FileChannel fileChannel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ByteBuffer buffer = ByteBuffer.allocate(<span class="number">48</span>);</span><br><span class="line">    <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">        <span class="comment">// 将fileChannel通道中的数据读取到buffer中并返回最后的写入位置</span></span><br><span class="line">        <span class="keyword">int</span> position = fileChannel.read(buffer);</span><br><span class="line">        <span class="comment">// -1说明fileChannel通道中的数据为空</span></span><br><span class="line">        <span class="keyword">if</span> (position &lt;= -<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 将buffer写模式翻转成读模式</span></span><br><span class="line">        buffer.flip();</span><br><span class="line">        <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">            <span class="keyword">char</span> ch = (<span class="keyword">char</span>) buffer.get();</span><br><span class="line">            System.out.print(ch);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 清空buffer</span></span><br><span class="line">        buffer.compact();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="1-4-SocketChannel"><a href="#1-4-SocketChannel" class="headerlink" title="1.4. SocketChannel"></a>1.4. <strong>SocketChannel</strong></h4><p>有两种Socket通道，一个是客户端的SocketChannel，一个是负责服务器端的Socket通道ServerSocketChannel。SocketChannel与OIO中的Socket类对应，ServerSocketChannel对应于OIO中的ServerSocket类相NIO。</p>
<p>两种Socket通道新增的通道都支持阻塞和非阻塞两种模式。在阻塞模式下的通道的创建、关闭、读写操作如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 非阻塞模式</span></span><br><span class="line"><span class="comment">  * 在非阻塞模式，我们可以设置 SocketChannel 为异步模式，这样我们的 connect，read，write 都是异步的了.</span></span><br><span class="line"><span class="comment">  * 非阻塞模式与选择器搭配会工作的更好，通过将一或多个SocketChannel注册到Selector，可以询问选择器哪个通道已经准备好了读取，写入等</span></span><br><span class="line"><span class="comment">  *</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TestNoBlockSocketChannel</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 操作一：创建</span></span><br><span class="line">    <span class="comment">// 这个是客户端的创建。当一个服务器端的ServerSocketChannel 接受到连接请求时，也会返回一个 SocketChannel 对象。</span></span><br><span class="line">    SocketChannel socketChannel = SocketChannel.open();</span><br><span class="line">    socketChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">    socketChannel.connect(<span class="keyword">new</span> InetSocketAddress(<span class="string">"127.0.0.1"</span>, <span class="number">8888</span>));</span><br><span class="line">    <span class="comment">// 确定连接是否建立</span></span><br><span class="line">    <span class="keyword">while</span> (!socketChannel.finishConnect()) &#123;</span><br><span class="line">        <span class="comment">//wait, or do something else...</span></span><br><span class="line">        <span class="comment">// 操作二：读取</span></span><br><span class="line">        write(socketChannel);</span><br><span class="line">        <span class="comment">//非阻塞模式下，write()方法在尚未写出任何内容时可能就返回了。所以需要在循环中调用write()。前面已经有例子了，这里就不赘述了。</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 操作三：写入数据</span></span><br><span class="line">        read(socketChannel);</span><br><span class="line">        <span class="comment">//非阻塞模式下,read()方法在尚未读取到任何数据时可能就返回了。所以需要关注它的int返回值，它会告诉你读取了多少字节。</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 操作四：关闭</span></span><br><span class="line">    socketChannel.close();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 阻塞模式</span></span><br><span class="line"><span class="comment">  *</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TestBlockSocketChannel</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 操作一：创建</span></span><br><span class="line">    <span class="comment">// 这个是客户端的创建。当一个服务器端的ServerSocketChannel 接受到连接请求时，也会返回一个 SocketChannel 对象。</span></span><br><span class="line">    SocketChannel socketChannel = SocketChannel.open();</span><br><span class="line">    socketChannel.connect(<span class="keyword">new</span> InetSocketAddress(<span class="string">"127.0.0.1"</span>, <span class="number">88888</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 操作二：读取</span></span><br><span class="line">    read(socketChannel);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 操作三：写入数据</span></span><br><span class="line">    write(socketChannel);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 操作四：关闭</span></span><br><span class="line">    socketChannel.close();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">read</span><span class="params">(ReadableByteChannel channel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ByteBuffer buffer = ByteBuffer.allocate(<span class="number">48</span>);</span><br><span class="line">    <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">        <span class="comment">// 将Channel通道中的数据读取到buffer中并返回最后的写入位置</span></span><br><span class="line">        <span class="keyword">int</span> position = channel.read(buffer);</span><br><span class="line">        <span class="comment">// -1说明Channel通道中的数据为空</span></span><br><span class="line">        <span class="keyword">if</span> (position &lt;= -<span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 将buffer写模式翻转成读模式</span></span><br><span class="line">        buffer.flip();</span><br><span class="line">        <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">            <span class="keyword">char</span> ch = (<span class="keyword">char</span>) buffer.get();</span><br><span class="line">            System.out.print(ch);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 清空buffer</span></span><br><span class="line">        buffer.compact();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">write</span><span class="params">(WritableByteChannel channel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">    buffer.clear();</span><br><span class="line">    buffer.put(str.getBytes());</span><br><span class="line">    buffer.flip();</span><br><span class="line">    <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">        channel.write(buffer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="ServerSocketChannel"><a href="#ServerSocketChannel" class="headerlink" title="ServerSocketChannel"></a>ServerSocketChannel</h4><p>ServerSocketChannel 顾名思义，是用在服务器为端的，可以监听客户端的 TCP 连接，例如:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 非阻塞模式</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TestNoBlockServerSocketChannel</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 打开 ServerSocketChannel</span></span><br><span class="line">    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();</span><br><span class="line">    <span class="comment">// 绑定通道</span></span><br><span class="line">    serverSocketChannel.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">8888</span>));</span><br><span class="line">    <span class="comment">// ServerSocketChannel可以设置成非阻塞模式。</span></span><br><span class="line">    serverSocketChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">    <span class="comment">// 监听新进来的连接</span></span><br><span class="line">    <span class="comment">// 通过 ServerSocketChannel.accept() 方法监听新进来的连接。</span></span><br><span class="line">    <span class="comment">// 当 accept()方法返回的时候,它返回一个包含新进来的连接的 SocketChannel。</span></span><br><span class="line">    <span class="comment">// 因此, accept()方法会一直阻塞到有新连接到达。</span></span><br><span class="line">    <span class="comment">// 通常不会仅仅只监听一个连接,在while循环中调用 accept()方法.</span></span><br><span class="line">    <span class="keyword">while</span>(<span class="keyword">true</span>)&#123;</span><br><span class="line">        SocketChannel socketChannel = serverSocketChannel.accept();</span><br><span class="line">        <span class="comment">// 在非阻塞模式下，accept() 方法会立刻返回，如果还没有新进来的连接,返回的将是null。</span></span><br><span class="line">        <span class="comment">// 因此，需要检查返回的SocketChannel是否是null.如：</span></span><br><span class="line">        <span class="keyword">if</span> (socketChannel!=<span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">//do something with socketChannel...</span></span><br><span class="line">            <span class="comment">// 读取</span></span><br><span class="line">            read(socketChannel);</span><br><span class="line">            <span class="comment">// 写入</span></span><br><span class="line">            write(socketChannel);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//当然,也可以在while循环中使用除了true以外的其它退出准则。</span></span><br><span class="line">    serverSocketChannel.close();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 阻塞模式</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TestBlockServerSocketChannel</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 打开 ServerSocketChannel</span></span><br><span class="line">    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();</span><br><span class="line">    <span class="comment">// 绑定通道</span></span><br><span class="line">    serverSocketChannel.bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">8888</span>));</span><br><span class="line">    <span class="comment">// 监听新进来的连接</span></span><br><span class="line">    <span class="comment">// 通过 ServerSocketChannel.accept() 方法监听新进来的连接。</span></span><br><span class="line">    <span class="comment">// 当 accept()方法返回的时候,它返回一个包含新进来的连接的 SocketChannel。</span></span><br><span class="line">    <span class="comment">// 因此, accept()方法会一直阻塞到有新连接到达。</span></span><br><span class="line">    <span class="comment">// 通常不会仅仅只监听一个连接,在while循环中调用 accept()方法.</span></span><br><span class="line">    <span class="keyword">while</span>(<span class="keyword">true</span>)&#123;</span><br><span class="line">        SocketChannel socketChannel = serverSocketChannel.accept();</span><br><span class="line">        <span class="comment">//do something with socketChannel...</span></span><br><span class="line">        <span class="comment">// 读取</span></span><br><span class="line">        read(socketChannel);</span><br><span class="line">        <span class="comment">// 写入</span></span><br><span class="line">        write(socketChannel);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//当然,也可以在while循环中使用除了true以外的其它退出准则。</span></span><br><span class="line">    serverSocketChannel.close();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="1-5-DatagramChannel"><a href="#1-5-DatagramChannel" class="headerlink" title="1.5. DatagramChannel"></a>1.5. <strong>DatagramChannel</strong></h4><p>Java NIO中的DatagramChannel是一个能收发UDP包的通道。因为UDP是无连接的网络协议，所以不能像其它通道那样读取和写入。它发送和接收的是数据包。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">TestDatagramChannel</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 打开 DatagramChannel</span></span><br><span class="line">    DatagramChannel channel = DatagramChannel.open();</span><br><span class="line">    channel.socket().bind(<span class="keyword">new</span> InetSocketAddress(<span class="number">9999</span>));</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 连接到特定的地址</span></span><br><span class="line">    <span class="comment">//channel.connect(new InetSocketAddress("localhost", 8888));</span></span><br><span class="line">    <span class="comment">// 当连接后，也可以使用read()和write()方法，就像在用传统的通道一样。只是在数据传送方面没有任何保证</span></span><br><span class="line">    <span class="comment">//int bytesRead = channel.read(buffer);</span></span><br><span class="line">    <span class="comment">//int bytesWritten = channel.write(buffer);</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 接受数据</span></span><br><span class="line">    <span class="comment">// 通过receive()方法从DatagramChannel接收数据</span></span><br><span class="line">    ByteBuffer buffer = ByteBuffer.allocate(<span class="number">48</span>);</span><br><span class="line">    <span class="comment">// receive()方法会将接收到的数据包内容复制到指定的Buffer. 如果Buffer容不下收到的数据，多出的数据将被丢弃。</span></span><br><span class="line">    channel.receive(buffer);</span><br><span class="line">    <span class="comment">// 将buffer写模式翻转成读模式</span></span><br><span class="line">    buffer.flip();</span><br><span class="line">    <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">        <span class="keyword">char</span> ch = (<span class="keyword">char</span>) buffer.get();</span><br><span class="line">        System.out.print(ch);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 清空buffer</span></span><br><span class="line">    buffer.compact();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 发送数据</span></span><br><span class="line">    <span class="comment">// 通过send()方法从DatagramChannel发送数据</span></span><br><span class="line">    buffer.clear();</span><br><span class="line">    buffer.put(str.getBytes());</span><br><span class="line">    buffer.flip();</span><br><span class="line">    <span class="comment">// 发送一串字符到”本机”服务器的UDP端口8888。</span></span><br><span class="line">    <span class="comment">// 因为服务端并没有监控这个端口，所以什么也不会发生。也不会通知你发出的数据包是否已收到，因为UDP在数据传送方面没有任何保证。</span></span><br><span class="line">    <span class="keyword">int</span> byteSend = channel.send(buffer, <span class="keyword">new</span> InetSocketAddress(<span class="string">"localhost"</span>, <span class="number">8888</span>));</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-Scatter-Gather"><a href="#2-Scatter-Gather" class="headerlink" title="2. Scatter/Gather"></a>2. Scatter/Gather</h3><p>Java NIO开始支持scatter/gather，scatter/gather用于描述从Channel（译者注：Channel在中文经常翻译为通道）中读取或者写入到Channel的操作。<br>分散（scatter）从Channel中读取是指在读操作时将读取的数据写入多个buffer中。因此，Channel将从Channel中读取的数据“分散（scatter）”到多个Buffer中。<br>聚集（gather）写入Channel是指在写操作时将多个buffer的数据写入同一个Channel，因此，Channel 将多个Buffer中的数据“聚集（gather）”后发送到Channel。</p>
<p>scatter / gather经常用于需要将传输的数据分开处理的场合，例如传输一个由消息头和消息体组成的消息，你可能会将消息体和消息头分散到不同的buffer中，这样你可以方便的处理消息头和消息体。</p>
<h4 id="Scattering-Reads"><a href="#Scattering-Reads" class="headerlink" title="Scattering Reads"></a><strong>Scattering Reads</strong></h4><p>Scattering Reads是指数据从一个channel读取到多个buffer中。如下图描述：</p>
<p><img src="/blog/assets/img/scatter.png" alt="Scattering Read"></p>
<p>代码示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ByteBuffer header = ByteBuffer.allocate(<span class="number">128</span>);</span><br><span class="line">ByteBuffer body   = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">ByteBuffer[] bufferArray = &#123; header, body &#125;;</span><br><span class="line">channel.read(bufferArray);</span><br></pre></td></tr></table></figure>

<p>注意buffer首先被插入到数组，然后再将数组作为channel.read() 的输入参数。read()方法按照buffer在数组中的顺序将从channel中读取的数据写入到buffer，当一个buffer被写满后，channel紧接着向另一个buffer中写。</p>
<p>Scattering Reads在移动下一个buffer前，必须填满当前的buffer，这也意味着它不适用于动态消息(译者注：消息大小不固定)。换句话说，如果存在消息头和消息体，消息头必须完成填充（例如 128byte），Scattering Reads才能正常工作。</p>
<h4 id="Gathering-Writes"><a href="#Gathering-Writes" class="headerlink" title="Gathering Writes"></a><strong>Gathering Writes</strong></h4><p>Gathering Writes是指数据从多个buffer写入到同一个channel。如下图描述：</p>
<p><img src="/blog/assets/img/gather.png" alt="Gathering Write"></p>
<p>代码示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ByteBuffer header = ByteBuffer.allocate(<span class="number">128</span>);</span><br><span class="line">ByteBuffer body   = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"><span class="comment">//write data into buffers</span></span><br><span class="line">ByteBuffer[] bufferArray = &#123; header, body &#125;;</span><br><span class="line">channel.write(bufferArray);</span><br></pre></td></tr></table></figure>

<p>buffers数组是write()方法的入参，write()方法会按照buffer在数组中的顺序，将数据写入到channel，注意只有position和limit之间的数据才会被写入。因此，如果一个buffer的容量为128byte，但是仅仅包含58byte的数据，那么这58byte的数据将被写入到channel中。因此与Scattering Reads相反，Gathering Writes能较好的处理动态消息。</p>
<p>学习于<a href="https://www.cnblogs.com/crazymakercircle/p/9826883.html" target="_blank" rel="noopener">疯狂创客圈</a>和<a href="http://ifeve.com/java-nio-scattergather/" target="_blank" rel="noopener">并发编程网</a></p>

    </div>

    
    
    

    
    <div>    
      
        <ul class="post-copyright">
          <li class="post-copyright-link">
          <strong>本文作者：</strong>
          <a href="/" title="欢迎访问 Chenyumeng 的个人博客">Chenyumeng</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文标题：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/05/23/Java%20NIO%20Channel/" title="Java NIO Channel">Java NIO Channel</a>
          </li>

          <li class="post-copyright-link">
            <strong>本文链接：</strong>
            <a href="https://ipvb.gitee.io/blog/2020/05/23/Java%20NIO%20Channel/" title="Java NIO Channel">https://ipvb.gitee.io/blog/2020/05/23/Java%20NIO%20Channel/</a>
          </li>

          <li class="post-copyright-date">
            <strong>发布时间： </strong>2020年5月23日 - 11时05分
          </li>  

          <li class="post-copyright-license">
            <strong>版权声明： </strong>
            本文由 Chenyumeng 原创。
          </li>
        </ul>
      
    </div>
      
  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\05\22\Java NIO Buffer\" rel="bookmark">Java NIO Buffer</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\05\23\Java NIO Selector\" rel="bookmark">Java NIO Selector</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\16\linux JDK安装\" rel="bookmark">linux JDK安装</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\ZooKeeper\" rel="bookmark">ZooKeeper单机与集群安装笔记</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\blog\2020\03\15\centOs7_Redis\" rel="bookmark">centOs7下安装Redis记录</a></div>
    </li>
  </ul>

        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/images/wechatpay.png" alt="Chenyumeng 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blog/images/alipay.png" alt="Chenyumeng 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <div>
        
          <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------　　　　本文结束　<i class="fa fa-heart"></i>　感谢您的阅读　　　　-------------</div>
    
</div>
        
      </div>

      <footer class="post-footer">
          
          <div class="post-tags">
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
              <a href="/blog/" rel="tag"><i class="fa fa-tag"></i> </a>
            
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2020/05/22/Java%20NIO%20Buffer/" rel="prev" title="Java NIO Buffer">
      <i class="fa fa-chevron-left"></i> Java NIO Buffer
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/05/23/Java%20NIO%20Selector/" rel="next" title="Java NIO Selector">
      Java NIO Selector <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

    <!-- 引入share.js -->
    
      <div data-weibo-title="分享到微博" data-qq-title="分享到QQ" data-douban-title="分享到豆瓣" class="social-share" class="share-component" data-disabled="twitter,facebook" data-description="Share.js - 一键分享到微博，QQ空间，腾讯微博，人人，豆瓣">分享到：</div>
    
  </div>


          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC80OTExNy8yNTYxMg=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-Java-NIO-Channel"><span class="nav-number">1.</span> <span class="nav-text">1. Java NIO Channel</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-Java-NIO-Channel的特点"><span class="nav-number">1.1.</span> <span class="nav-text">1.1. Java NIO Channel的特点</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-Channel类型"><span class="nav-number">1.2.</span> <span class="nav-text">1.2. Channel类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-FileChannel"><span class="nav-number">1.3.</span> <span class="nav-text">1.3. FileChannel</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-4-SocketChannel"><span class="nav-number">1.4.</span> <span class="nav-text">1.4. SocketChannel</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#ServerSocketChannel"><span class="nav-number">1.5.</span> <span class="nav-text">ServerSocketChannel</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-5-DatagramChannel"><span class="nav-number">1.6.</span> <span class="nav-text">1.5. DatagramChannel</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-Scatter-Gather"><span class="nav-number">2.</span> <span class="nav-text">2. Scatter&#x2F;Gather</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Scattering-Reads"><span class="nav-number">2.1.</span> <span class="nav-text">Scattering Reads</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Gathering-Writes"><span class="nav-number">2.2.</span> <span class="nav-text">Gathering Writes</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Chenyumeng"
      src="/blog/images/touxiang.JPG">
  <p class="site-author-name" itemprop="name">Chenyumeng</p>
  <div class="site-description" itemprop="description">用来记录自己学习中所遇到的问题以及如何解决和自己所学知识的理解</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">32</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">29</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/chen-yumeng" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;chen-yumeng" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/3123221441" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;3123221441" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      Links
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://github.com/" title="https:&#x2F;&#x2F;github.com&#x2F;" rel="noopener" target="_blank">Github</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chenyumeng</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">390k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">5:55</span>
</div>

        






  <script>
  function leancloudSelector(url) {
    url = encodeURI(url);
    return document.getElementById(url).querySelector('.leancloud-visitors-count');
  }
  if (CONFIG.page.isPost) {
    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.id);
      var title = visitors.dataset.flagTitle;

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url })))
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .then(response => response.json())
              .catch(error => {
                console.error('Failed to save visitor count', error);
              })
          } else {
              Counter('post', '/classes/Counter', { title, url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  } else {
    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.id);
      });

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url: { '$in': entries } })))
        .then(response => response.json())
        .then(({ results }) => {
          for (let url of entries) {
            let target = results.find(item => item.url === url);
            leancloudSelector(url).innerText = target ? target.time : 0;
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }
  }

  fetch('https://app-router.leancloud.cn/2/route?appId=')
    .then(response => response.json())
    .then(({ api_server }) => {
      var Counter = (method, url, data) => {
        return fetch(`https://${api_server}/1.1${url}`, {
          method,
          headers: {
            'X-LC-Id'     : '',
            'X-LC-Key'    : '',
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    });
  </script>


      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

  <script src="/dist/js/social-share.min.js"></script>
</body>
</html>
